package com.gzhryc.weixin.api.resource;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.weixin.gzh.AbsWeixinApi;
import com.gzhryc.weixin.api.DefaultApiResponse;
import com.gzhryc.weixin.gzh.models.AccessToken;
import com.gzhryc.weixin.api.resource.msg.req.AddNewsSendGroupRequest;
import com.gzhryc.weixin.api.resource.msg.req.SendNewsRequest;
import com.gzhryc.weixin.api.resource.msg.req.SendTemplateMsgRequest;
import com.gzhryc.weixin.api.resource.msg.resp.AddSendGroupResponse;
import com.gzhryc.weixin.api.resource.msg.resp.SendResponse;
import com.gzhryc.weixin.api.resource.msg.resp.SendTemplateMsgResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class WxChatApi extends AbsWeixinApi{

	private Logger log = Logger.getLogger(WxChatApi.class);
	
	public WxChatApi(AccessToken accessToken) {
		super(accessToken);
	}

	/**
	 * 添加微信图文发送组
	 * https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
	 * @param request
	 * @return
	 */
	public AddSendGroupResponse addNewsSendGroup(AddNewsSendGroupRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/media/uploadnews")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .build();
			
			StringEntity strEntity = new StringEntity(JsonTools.toJson(request),
			        ContentType.create("application/json", Consts.UTF_8));
			
			HttpPost httppost = new HttpPost(uri);
			httppost.setEntity(strEntity);
			
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				AddSendGroupResponse result = JsonTools.fromJson(str,AddSendGroupResponse.class);
				if(result != null && StringUtils.isNotBlank(result.getType())){
					return result;
				}
				accessToken.queuePut(JsonTools.fromJson(str,DefaultApiResponse.class));
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 群发微信图文
	 * https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN
	 * @param request
	 * @return
	 */
	public SendResponse sendArticles(SendNewsRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/message/mass/sendall")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .build();
			
			StringEntity strEntity = new StringEntity(JsonTools.toJson(request),
			        ContentType.create("application/json", Consts.UTF_8));
			
			HttpPost httppost = new HttpPost(uri);
			httppost.setEntity(strEntity);
			
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				SendResponse result = JsonTools.fromJson(str,SendResponse.class);
				if(result.getErrcode() != 0){
					DefaultApiResponse temp = new DefaultApiResponse();
					temp.setErrcode(result.getErrcode());
					temp.setErrmsg(result.getErrmsg());
					accessToken.queuePut(temp);
				}
				return result;
			}
		} catch(Exception e){
			log.error(e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 发送模板消息
	 * @param request
	 * @return
	 */
	public SendTemplateMsgResponse sendTemplateMsg(SendTemplateMsgRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/message/template/send")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .build();
			
			StringEntity strEntity = new StringEntity(JsonTools.toJson(request),
			        ContentType.create("application/json", Consts.UTF_8));
			
			HttpPost httppost = new HttpPost(uri);
			httppost.setEntity(strEntity);
			
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				SendTemplateMsgResponse result = JsonTools.fromJson(str,SendTemplateMsgResponse.class);
				if(result.getErrcode() != 0){
					DefaultApiResponse temp = new DefaultApiResponse();
					temp.setErrcode(result.getErrcode());
					temp.setErrmsg(result.getErrmsg());
					accessToken.queuePut(temp);
				}
				return result;
			}
		} catch(Exception e){
			log.error(e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
}
